/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.common.filter;

import com.huawei.housekeeper.common.constant.CommonConstants;
import com.huawei.housekeeper.common.properties.ResourcesExcluderProperties;
import com.huawei.housekeeper.common.utils.TokenUtil;

import lombok.extern.log4j.Log4j2;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息解析过滤器
 *
 * @author wwx1136431
 * @since 2022-04-25
 */
@Log4j2
@WebFilter(filterName = "resloveUserInfoFilter", urlPatterns = "/*")
public class ResloveUserInfoFilter implements Filter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private ResourcesExcluderProperties resourcesExcluderProperties;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;

            String[] excludedUris = resourcesExcluderProperties.getExcludedUris();
            for (String uris : excludedUris) {
                if (pathMatcher.match(uris, request.getRequestURI())) {
                    log.info("requestUri: " + request.getRequestURI());
                    filterChain.doFilter(request, response);
                    return;
                }
            }
            try {
                String userName = tokenUtil.getUserNameFromHeader();
                String userId = tokenUtil.getUidFromHeader();
                request.setAttribute(CommonConstants.User.USER_ID, userId);
                request.setAttribute(CommonConstants.User.USER_NAME, userName);

                // 将用户信息加到MDC当中
                MDC.put(CommonConstants.User.USER_NAME, userName);
                MDC.put(CommonConstants.User.USER_ID, userId);
                filterChain.doFilter(request, response);
            } finally {
                MDC.clear();
                // 放入用户username
                request.setAttribute(CommonConstants.User.USER_NAME, null);
                // 放入用户userId
                request.setAttribute(CommonConstants.User.USER_ID, null);
            }
        }
    }
}
